package com.example.demo.controller;

import com.example.demo.domain.Ticket;
import com.example.demo.service.TicketService;
import com.example.demo.util.MultipartFileToFile;
import com.example.demo.util.ParseUsername;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.auth.DefaultBceCredentials;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping
@CrossOrigin
@Slf4j
public class TicketController {
    @Autowired
    private TicketService ticketService;
    private List<Ticket> ticketList;

    String ACCESS_KEY_ID = "79c9cba51f0a4df1a6281aab51cdad3e";      // 用户的Access Key ID
    String SECRET_ACCESS_KEY = "b21aa6a38adf439fa2dd26c6033e1311";  // 用户的Secret Access Key
    String ENDPOINT = "http://bj.bcebos.com";                       // 用户自己指定的域名
    UUID uuid;  //随机生成的图片名

    /**
     * @Description:  获取对应应审核票据列表
     * @Param:  nowpage：当前页码
     * @Param: pagesize：页码大小
     * @Param: select：选择的搜索种类
     * @Param: searchContent：搜索内容
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('addTicket','tickets:addticket:list') or hasPermission('checkTicket','tickets:checkticket:list')")
    @GetMapping(value = "/unchecked-ticket")
    public String getUncheckedTickets(@RequestParam("nowPage")Integer nowPage,@RequestParam("pageSize")Integer pageSize,
                                      @RequestParam("select")String select,@RequestParam("searchContent")String searchContent,
                                      @RequestParam("process")Integer process){
        if(select.equals("employee-name")){
            ticketList=ticketService.getUncheckedTicketByEmployeeName(searchContent,process);
            // System.out.println(select);
        }else if(select.equals("department")){
            ticketList=ticketService.getUncheckedTickerByDepartment(searchContent,process);
        }else{
            ticketList=ticketService.getAllUncheckedTicket(searchContent,process);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",ticketList.size());
        List<Ticket> tickets = ticketList.subList((nowPage - 1) * pageSize,Math.min( nowPage * pageSize,ticketList.size()));
        JSONArray jsonArray = new JSONArray();
        for (Ticket temp:tickets){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("receipt_id",temp.getId());
            jsonObject1.put("employeeName",temp.getEmployeeName());
            jsonObject1.put("department",temp.getDepartment());
            jsonObject1.put("sex",temp.getSex());
            jsonObject1.put("age",temp.getAge());
            jsonObject1.put("fee",temp.getFee());
            jsonObject1.put("report",temp.getReport());
            Date date = temp.getDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            jsonObject1.put("date",time);
            jsonObject1.put("state",temp.getState());
            jsonObject1.put("process",temp.getCheckProcess());
            if(temp.getAuditor1()==null){
                jsonObject1.put("auditor1","");
                jsonObject1.put("opinion1",temp.getOpinion1());
            }else{
                jsonObject1.put("auditor1",temp.getAuditor1());
                jsonObject1.put("opinion1",temp.getOpinion1());
            }
            if(temp.getAuditor2()==null){
                jsonObject1.put("auditor2","");
                jsonObject1.put("opinion2",temp.getOpinion2());
            }else{
                jsonObject1.put("auditor2",temp.getAuditor2());
                jsonObject1.put("opinion2",temp.getOpinion2());
            }
            if(temp.getAuditor3()==null){
                jsonObject1.put("auditor3","");
                jsonObject1.put("opinion3",temp.getOpinion3());
            }else{
                jsonObject1.put("auditor3",temp.getAuditor3());
                jsonObject1.put("opinion3",temp.getOpinion3());
            }
            if(temp.getDate1()!=null){
                Date date1=temp.getDate1();
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time1 = dateFormat1.format(date1);
                jsonObject1.put("date1",time1);
            }
            if(temp.getDate2()!=null){
                Date date2=temp.getDate2();
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time2 = dateFormat2.format(date2);
                jsonObject1.put("date2",time2);
            }
            if(temp.getDate3()!=null){
                Date date3=temp.getDate3();
                SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time3 = dateFormat3.format(date3);
                jsonObject1.put("date3",time3);
            }
            jsonArray.add(jsonObject1);
        }
        jsonObject.put("tickets",jsonArray);
        return jsonObject.toString();
    }

    /**
     * @Description:  获取审核中票据列表
     * @Param:  nowPage：当前页码
     * @Param: pageSize：页码大小
     * @Param: select：选择的搜索种类
     * @Param: searchContent：搜索内容
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('allTicket','tickets:allticket:checkinglist')")
    @GetMapping(value = "/checking-tickets")
    public String getCheckingTickets(@RequestParam("nowPage")Integer nowPage,@RequestParam("pageSize")Integer pageSize,
                                    @RequestParam("select")String select,@RequestParam("searchContent")String searchContent){
        if(select.equals("employee-name")){
            ticketList=ticketService.getCheckingTicketsByEmployeeName(searchContent);
            // System.out.println(select);
        }else if(select.equals("department")){
            ticketList=ticketService.getCheckingTicketsByDepartment(searchContent);
        }else{
            ticketList=ticketService.getCheckingTickets(searchContent);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",ticketList.size());
        List<Ticket> tickets = ticketList.subList((nowPage - 1) * pageSize,Math.min( nowPage * pageSize,ticketList.size()));
        JSONArray jsonArray = new JSONArray();
        for (Ticket temp:tickets){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("receipt_id",temp.getId());
            jsonObject1.put("employeeName",temp.getEmployeeName());
            jsonObject1.put("department",temp.getDepartment());
            jsonObject1.put("sex",temp.getSex());
            jsonObject1.put("age",temp.getAge());
            jsonObject1.put("fee",temp.getFee());
            jsonObject1.put("report",temp.getReport());
            Date date=temp.getDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            jsonObject1.put("date",time);
            jsonObject1.put("state",temp.getState());
            jsonObject1.put("process",temp.getCheckProcess());
            if(temp.getAuditor1()==null){
                jsonObject1.put("auditor1","");
                jsonObject1.put("opinion1",temp.getOpinion1());
            }else{
                jsonObject1.put("auditor1",temp.getAuditor1());
                jsonObject1.put("opinion1",temp.getOpinion1());
            }
            if(temp.getAuditor2()==null){
                jsonObject1.put("auditor2","");
                jsonObject1.put("opinion2",temp.getOpinion2());
            }else{
                jsonObject1.put("auditor2",temp.getAuditor2());
                jsonObject1.put("opinion2",temp.getOpinion2());
            }
            if(temp.getAuditor3()==null){
                jsonObject1.put("auditor3","");
                jsonObject1.put("opinion3",temp.getOpinion3());
            }else{
                jsonObject1.put("auditor3",temp.getAuditor3());
                jsonObject1.put("opinion3",temp.getOpinion3());
            }
            if(temp.getDate1()!=null){
                Date date1=temp.getDate1();
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time1 = dateFormat1.format(date1);
                jsonObject1.put("date1",time1);
            }
            if(temp.getDate2()!=null){
                Date date2=temp.getDate2();
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time2 = dateFormat2.format(date2);
                jsonObject1.put("date2",time2);
            }
            if(temp.getDate3()!=null){
                Date date3=temp.getDate3();
                SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time3 = dateFormat3.format(date3);
                jsonObject1.put("date3",time3);
            }
            jsonArray.add(jsonObject1);
        }
        jsonObject.put("tickets",jsonArray);
        return jsonObject.toString();
    }

    /**
     * @Description:  获取已通过票据列表
     * @Param:  nowPage：当前页码
     * @Param: pageSize：页码大小
     * @Param: select：选择的搜索种类
     * @Param: searchContent：搜索内容
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('allTicket','tickets:allticket:passedlist')")
    @GetMapping(value = "/passed-tickets")
    public String getPassedTickets(@RequestParam("nowPage")Integer nowPage,@RequestParam("pageSize")Integer pageSize,
                                     @RequestParam("select")String select,@RequestParam("searchContent")String searchContent){
        if(select.equals("employee-name")){
            ticketList=ticketService.getPassedTicketsByEmployeeName(searchContent);
            // System.out.println(select);
        }else if(select.equals("department")){
            ticketList=ticketService.getPassedTicketsByDepartment(searchContent);
        }else{
            ticketList=ticketService.getPassedTickets(searchContent);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",ticketList.size());
        List<Ticket> tickets = ticketList.subList((nowPage - 1) * pageSize,Math.min( nowPage * pageSize,ticketList.size()));
        JSONArray jsonArray = new JSONArray();
        for (Ticket temp:tickets){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("receipt_id",temp.getId());
            jsonObject1.put("employeeName",temp.getEmployeeName());
            jsonObject1.put("department",temp.getDepartment());
            jsonObject1.put("sex",temp.getSex());
            jsonObject1.put("age",temp.getAge());
            jsonObject1.put("fee",temp.getFee());
            jsonObject1.put("report",temp.getReport());
            Date date=temp.getDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            jsonObject1.put("date",time);
            jsonObject1.put("state",temp.getState());
            jsonObject1.put("process",temp.getCheckProcess());
            jsonObject1.put("opinion1",temp.getOpinion1());
            jsonObject1.put("opinion2",temp.getOpinion2());
            jsonObject1.put("opinion3",temp.getOpinion3());
            jsonObject1.put("auditor1",temp.getAuditor1());
            jsonObject1.put("auditor2",temp.getAuditor2());
            jsonObject1.put("auditor3",temp.getAuditor3());
            Date date1=temp.getDate1();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String time1 = dateFormat1.format(date1);
            jsonObject1.put("date1",time1);
            Date date2=temp.getDate2();
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String time2 = dateFormat2.format(date2);
            jsonObject1.put("date2",time2);
            Date date3=temp.getDate3();
            SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String time3 = dateFormat3.format(date3);
            jsonObject1.put("date3",time3);
            jsonArray.add(jsonObject1);
        }
        jsonObject.put("tickets",jsonArray);
        return jsonObject.toString();
    }

    /**
     * @Description:  获取已驳回票据列表
     * @Param:  nowPage：当前页码
     * @Param: pageSize：页码大小
     * @Param: select：选择的搜索种类
     * @Param: searchContent：搜索内容
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('allTicket','tickets:allticket:refusedlist')")
    @GetMapping(value = "/refused-tickets")
    public String getRefusedTickets(@RequestParam("nowPage")Integer nowPage,@RequestParam("pageSize")Integer pageSize,
                                   @RequestParam("select")String select,@RequestParam("searchContent")String searchContent){
        if(select.equals("employee-name")){
            ticketList=ticketService.getRefusedTicketsByEmployeeName(searchContent);
            // System.out.println(select);
        }else if(select.equals("department")){
            ticketList=ticketService.getRefusedTicketsByDepartment(searchContent);
        }else{
            ticketList=ticketService.getRefusedTickets(searchContent);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",ticketList.size());
        List<Ticket> tickets = ticketList.subList((nowPage - 1) * pageSize,Math.min( nowPage * pageSize,ticketList.size()));
        JSONArray jsonArray = new JSONArray();
        for (Ticket temp:tickets){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("receipt_id",temp.getId());
            jsonObject1.put("employeeName",temp.getEmployeeName());
            jsonObject1.put("department",temp.getDepartment());
            jsonObject1.put("sex",temp.getSex());
            jsonObject1.put("age",temp.getAge());
            jsonObject1.put("fee",temp.getFee());
            jsonObject1.put("report",temp.getReport());
            Date date=temp.getDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            jsonObject1.put("date",time);
            jsonObject1.put("state",temp.getState());
            jsonObject1.put("process",temp.getCheckProcess());
            if(temp.getAuditor1()==null){
                jsonObject1.put("auditor1","");
                jsonObject1.put("opinion1",temp.getOpinion1());
            }else{
                jsonObject1.put("auditor1",temp.getAuditor1());
                jsonObject1.put("opinion1",temp.getOpinion1());
            }
            if(temp.getAuditor2()==null){
                jsonObject1.put("auditor2","");
                jsonObject1.put("opinion2",temp.getOpinion2());
            }else{
                jsonObject1.put("auditor2",temp.getAuditor2());
                jsonObject1.put("opinion2",temp.getOpinion2());
            }
            if(temp.getAuditor3()==null){
                jsonObject1.put("auditor3","");
                jsonObject1.put("opinion3",temp.getOpinion3());
            }else{
                jsonObject1.put("auditor3",temp.getAuditor3());
                jsonObject1.put("opinion3",temp.getOpinion3());
            }
            if(temp.getDate1()!=null){
                Date date1=temp.getDate1();
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time1 = dateFormat1.format(date1);
                jsonObject1.put("date1",time1);
            }
            if(temp.getDate2()!=null){
                Date date2=temp.getDate2();
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time2 = dateFormat2.format(date2);
                jsonObject1.put("date2",time2);
            }
            if(temp.getDate3()!=null){
                Date date3=temp.getDate3();
                SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String time3 = dateFormat3.format(date3);
                jsonObject1.put("date3",time3);
            }
            jsonArray.add(jsonObject1);
        }
        jsonObject.put("tickets",jsonArray);
        return jsonObject.toString();
    }

    /**
     * @Description: 上传票据到百度对象存储
     * @Param:  file: 上传的图片
     * @return:  票据存储情况
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @PostMapping(value="/upload")
    public String upload(@RequestParam("imagefile") MultipartFile file) throws Exception{
        // 初始化一个BosClient
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        config.setEndpoint(ENDPOINT);
        BosClient client = new BosClient(config);
        // 将MultipartFile转化为File
        //System.out.println("bbb");
        File tempFile= MultipartFileToFile.MultipartFileToFile(file);
        // 生成随机的文件名
        uuid=UUID.randomUUID();
        String uuidStr=uuid.toString();
        // 以文件形式上传Object
        client.putObject("tickets", uuidStr+".jpeg", tempFile);
        return uuidStr+".jpeg";
    }

    /**
     * @Description: 添加票据
     * @Param: ticket：票据实体
     * @return: 前端传来的票据实体
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @PostMapping(value = "/wx-addticket")
    public Ticket addWxTicket( Ticket ticket){
       // System.out.println("aaa");
        ticket.setPicture(uuid.toString()+".jpeg");
        log.info("用户"+ ParseUsername.getUsername()+"上传了医疗报销单。");
        return ticketService.addTicket(ticket);
    }

    /**
     * @Description: 添加票据
     * @Param: ticket：票据实体
     * @return: 前端传来的票据实体
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('addTicket','tickets:addticket:add')")
    @PostMapping(value = "/addticket")
    public Ticket addTicket(@RequestBody Ticket ticket){
        // System.out.println("aaa");
        log.info("管理员"+ ParseUsername.getUsername()+"在后台上传了用户"+ticket.getWorkNumber()+"的医疗报销单。");
        return ticketService.addTicket(ticket);
    }


    /**
     * @Description: 根据ID获取票据详细信息
     * @Param:  id：票据ID
     * @return:  票据实体
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/ticket")
    public Ticket getTicketById(@RequestParam("receipt_id")Integer id){
        return ticketService.getTicketById(id);
    }

    /**
     * @Description: 根据ID删除某条票据
     * @Param:  id: 票据ID
     * @return:  无
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('addTicket','tickets:addticket:delete')")
    @DeleteMapping(value = "/ticket")
    public void deleteTicketById(@RequestParam("receipt_id")Integer id){
        Ticket ticket=ticketService.getTicketById(id);
        log.info("管理员"+ ParseUsername.getUsername()+"删除了一条用户"+ticket.getWorkNumber()+"的医疗报销单据。");
        ticketService.deleteTicketById(id);
    }

    /**
     * @Description: 审核通过
     * @Param: id: 票据ID
     *         process: 审核进程
     *         auditor: 审核人
     *         opinion: 审核意见
     * @return: 是否审核通过
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('checkTicket','tickets:checkticket:pass')")
    @GetMapping(value = "/pass-ticket")
    public boolean passTicket(@RequestParam("receipt_id")Integer id,
                              @RequestParam("process")Integer process,
                              @RequestParam("auditor")String auditor,
                              @RequestParam("opinion")String opinion){
        if(ticketService.pass(id,process,auditor,opinion)==null)
            return false;
        log.info("审核人"+auditor+ "审核通过了一条医疗报销单据，报销票据id:"+id);
        return true;
    }

    /**
     * @Description: 审核驳回
     * @Param: id: 票据ID
     *         process: 审核进程
     *         auditor: 审核人
     *         opinion: 审核意见
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('checkTicket','tickets:checkticket:refuse')")
    @GetMapping(value = "/refuse-ticket")
    public boolean refuseTicket(@RequestParam("receipt_id")Integer id,
                                @RequestParam("process")Integer process,
                                @RequestParam("auditor")String auditor,
                                @RequestParam("opinion")String opinion){
        if(ticketService.refuse(id,process,auditor,opinion)==null)
            return false;
        log.info("审核人"+auditor+ "审核驳回了一条医疗报销单据，报销票据id:"+id);
        return true;
    }

    /**
     * @Description: 返回职工已审核票据列表给微信小程序端
     * @Param: worknumber: 职工工号
     * @return: 票据列表
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/wx-checked-ticket")
    public List<Ticket> getWxCheckedTicketByWorkNumber(@RequestParam("worknumber") String workNumber){
        return ticketService.findCheckedTicketByWorkNumber(workNumber);
    }

    /**
     * @Description: 返回职工审核中票据列表给微信小程序端
     * @Param:  worknumber: 职工工号
     * @return:  票据列表
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/wx-unchecked-ticket")
    public List<Ticket> getWxUncheckedTicketByWorkNumber(@RequestParam("worknumber") String workNumber){
        return ticketService.findUncheckedTicketByWorkNumber(workNumber);
    }

    /**
     * @Description: 返回票据影像url给微信小程序端
     * @Param:  id：票据ID
     * @return:  票据存储地址
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @GetMapping(value = "/ticketImageUrl")
    public String getImageUrl(@RequestParam("receipt_id")Integer id){
        Ticket ticket=ticketService.getTicketById(id);
        String picture=ticket.getPicture();
        // 初始化一个BosClient
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        config.setEndpoint(ENDPOINT);
        BosClient client = new BosClient(config);
        URL url = client.generatePresignedUrl("tickets", picture,1800);
        return url.toString();
    }

    /**
     * @Description: 返回给定年份每月报销数组
     * @param year 指定年份
     * @return:  每月报销数目的数组
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('reports','statistics:reports:check')")
    @GetMapping(value = "/month-amount")
    public List<Integer> getMonthAmount(@RequestParam("year")Integer year){
        return ticketService.getMonthlyAmount(year);
    }

    /**
     * @Description: 返回给定年份各报销范围的报销单数量
     * @param year 指定年份
     * @return:  每报销范围的数量
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('reports','statistics:reports:check')")
    @GetMapping(value = "/ratio")
    public String getRatio(@RequestParam("year")Integer year){
        return ticketService.getRatio(year);
    }
}
